<?php

namespace app\models;

use think\Model;

class Business extends Model
{
    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'created';
    protected $updateTime = 'updated';

    /**
     * 资产变动变更记录
     * $type = 1 入账 2提现
     * @return void
     */
    public static function MoneyEdit($businessid, $type = 0, $money = 0, $info = '', $source = 0, $comeuser_id = 0)
    {
        if ($money != 0 && $businessid > 0) {
            $business = (new Business())->where('id', $businessid)->find();
            if (empty($business)) {
                throw new \Exception("商户不存在，请重试", 100);
            }
            if ($money < 0 && $business['money'] < $money) {
                throw new \Exception("资产不足，请重试", 100);
            }
            $res = (new Business())->where(['id' => $business['id'], 'money' => $business['money']])->setInc('money', $money);
            if (!$res) {
                throw new \Exception("资产修改失败，请重试", 100);
            }
            $res2 = (new BussinessLog())->save([
                'timeid' => time(),
                'user_id' => $business['id'],
                'comeuser_id' => $comeuser_id,
                'befores' => $business['money'],
                'money' => $money,
                'after' => ($business['money'] + $money),
                'type' => $type,
                'info' => $info,
                'source' => $source
            ]);
            if (!$res2) {
                throw new \Exception("资产记录失败，请重试", 100);
            }
        }
    }
}
